<template>
    <!-- 就诊人组件的静态结构 -->
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span>就诊人管理</span>
                <el-button class="button" type="success" :icon="User" @click="addUser">添加就诊人</el-button>
            </div>
        </template>
        <!-- 就诊人模块-展示就诊人信息卡片 -->
        <div class="visitors" v-if="cardType === 'list'">
            <Visitor class="item" v-for="(user, idx) in userArr" :key="user.id" :user="user" :index="idx"
                @edit="editUser" @removeUser="removeUser" :showDelete="true" />
        </div>
        <div class="form" v-if="cardType === 'edit'">
            <el-divider content-position="left">就诊人信息</el-divider>
            <el-form style="width:60%;margin:10px auto" label-width="100px">
                <el-form-item label="就诊人姓名" prop="name">
                    <el-input placeholder="请输入就诊人姓名" v-model="userParams.name" />
                </el-form-item>
                <el-form-item label="证件类型" prop="zone">
                    <el-select placeholder="请选择证件类型" v-model="userParams.certificatesType">
                        <el-option v-for="item in certationArr" :key="item.id" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="证件号码" prop="time">
                    <el-input placeholder="请输入证件号码" v-model="userParams.certificatesNo" />
                </el-form-item>
                <el-form-item label="就诊人性别" prop="time">
                    <el-radio-group v-model="userParams.sex">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="time">
                    <el-date-picker value-format="YYYY-MM-DD" type="date" placeholder="请选择日期"
                        v-model="userParams.birthdate" />
                </el-form-item>
                <el-form-item label="手机号码" prop="time">
                    <el-input placeholder="请输入手机号码" v-model="userParams.phone" />
                </el-form-item>
            </el-form>
            <el-divider content-position="left">建档信息</el-divider>
            <el-form style="width:60%;margin:10px auto" label-width="100px">
                <el-form-item label="婚姻状况" prop="name">
                    <el-radio-group v-model="userParams.isMarry">
                        <el-radio :label="1">已婚</el-radio>
                        <el-radio :label="0">未婚</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="自费/医保" prop="name">
                    <el-radio-group v-model="userParams.isInsure">
                        <el-radio :label="1">自费</el-radio>
                        <el-radio :label="0">医保</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="居住城市" prop="zone">
                    <el-cascader :props="props" v-model="userParams.addressSelected" />
                </el-form-item>
                <el-form-item label="详细地址" prop="time">
                    <el-input placeholder="请输入就诊人的详细地址" v-model="userParams.address" />
                </el-form-item>
            </el-form>
            <el-divider content-position="left">联系人信息（选填）</el-divider>
            <el-form style="width:60%;margin:10px auto" label-width="100px">
                <el-form-item label="联系人姓名" prop="name">
                    <el-input placeholder="请输入联系人姓名" v-model="userParams.contactsName" />
                </el-form-item>
                <el-form-item label="证件类型" prop="zone">
                    <el-select placeholder="请选择证件类型" v-model="userParams.contactsCertificatesType">
                        <el-option v-for="item in certationArr" :key="item.id" :label="item.name"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="证件号码" prop="time">
                    <el-input placeholder="请输入证件号码" v-model="userParams.contactsCertificatesNo" />
                </el-form-item>
                <el-form-item label="手机号码" prop="time">
                    <el-input placeholder="请输入手机号码" v-model="userParams.contactsPhone" />
                </el-form-item>
            </el-form>
            <div class="button-group">
                <el-button class="button" type="primary" @click="submit">提交</el-button>
                <el-button class="button" type="default" @click="reset">重置</el-button>
            </div>
        </div>
    </el-card>
</template>

<script setup lang="ts">
import type { CascaderProps } from "element-plus";
import { User } from "@element-plus/icons-vue";
import { reqGetUser } from "@/api/hospital";
import { reqCertationType, reqCity, reqAddOrUpdateUser } from "@/api/user";
import { onMounted, ref, reactive, watch } from "vue";
import type { UserResponseData, UserArr } from "@/api/hospital/type";
import type {
    CertationTypeResponseData,
    CertationArr,
    AddOrUpdateUser,
} from "@/api/user/type";
//引入路由器与路由方法
import { useRouter, useRoute } from "vue-router";
const $route = useRoute();
const $router = useRouter();
import { ElMessage } from "element-plus";

const userArr = ref<UserArr>([]);

// 用于切换卡片的展示内容
const cardType = ref<string>("list");

const certationArr = ref<CertationArr>([]);

// 居住城市级联选择器的属性数据
const props: CascaderProps = {
    lazy: true,
    async lazyLoad(node: any, resolve) {
        const res: any = await reqCity(node.data.id || "86");

        // 整理数据
        const data = res.data.map((item: any) => {
            return {
                id: item.id,
                value: item.value,
                label: item.name,
                leaf: !item.hasChildren,
            };
        });
        resolve(data);
    },
}

// 存储新增/编辑就诊人信息数据
const userParams = reactive<AddOrUpdateUser>({
    name: "",
    certificatesType: "",
    certificatesNo: "",
    sex: 0,
    birthdate: "",
    phone: "",
    isMarry: 0,
    isInsure: 0,
    addressSelected: [],
    address: "",
    contactsName: "",
    contactsCertificatesType: "",
    contactsCertificatesNo: "",
    contactsPhone: "",
})

const addUser = () => {
    reset();
    cardType.value = "edit";
};

//子组件自定义事件:删除按钮触发
const removeUser = () => {
    //再次获取全部的就诊人的信息
    getAllUser();
}

const editUser = (user: AddOrUpdateUser) => {
    cardType.value = "edit";
    // 为就诊人信息进行赋值
    Object.assign(userParams, user);
};

// 提交就诊人信息，添加新的就诊人或更新已有就诊人的信息
const submit = async () => {
    try {
        //要么新增用户成功|更新已有的用户成功
        await reqAddOrUpdateUser(userParams);
        //提示文字
        ElMessage({
            type: "success",
            message: userParams.id ? "更新成功" : "新增成功",
        });
        //提交按钮的时候判断是不是从预约挂号而来
        if ($route.query.type) {
            $router.back();
        } else {
            cardType.value = 'list';
        }
        //在获取全部的就诊人的信息
        getAllUser();
    } catch (error) {
        ElMessage({
            type: "error",
            message: userParams.id ? "更新失败" : "新增失败",
        });
    }
};

const reset = () => {
    Object.assign(userParams, {
        id: null,
        name: "",
        certificatesType: "",
        certificatesNo: "",
        sex: 0,
        birthdate: "",
        phone: "",
        isMarry: 0,
        isInsure: 0,
        addressSelected: [],
        address: "",
        contactsName: "",
        contactsCertificatesType: "",
        contactsCertificatesNo: "",
        contactsPhone: "",
    });
};

const getAllUser = async () => {
    const res: UserResponseData = await reqGetUser();
    if (res.code === 200) {
        userArr.value = res.data;
    }
};

const getCertationType = async () => {
    const res: CertationTypeResponseData = await reqCertationType();
    if (res.code === 200) {
        certationArr.value = res.data;
    }
}
onMounted(() => {
    getAllUser()
    // 获取证件类型数据
    getCertationType()

    // 判断当前页面是否是从预约挂号跳转而来
    if ($route.query.type == 'add') {
        cardType.value = "edit";
    } else if ($route.query.type == 'edit') {
        cardType.value = "edit";
    }
});
// 监听就诊人的请求结果
watch(
    () => userArr.value,
    () => {
        if ($route.query.type == "edit") {
            let user = userArr.value.find((item: any) => {
                return item.id == $route.query.id;
            });
            Object.assign(userParams, user)
        }
    }
);
</script>

<style scoped lang="scss">
.card-header {
    display: flex;
    justify-content: space-between;
}

.visitors {
    display: flex;
    flex-wrap: wrap;

    .item {
        width: 30%;
        margin: 10px
    }
}

.button-group {
    display: flex;
    justify-content: center
}
</style>